import { Component, OnInit, ViewChild, OnDestroy, AfterContentInit } from '@angular/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
import { NzMessageService, UploadFile, NzModalService, NzNotificationService } from 'ng-zorro-antd';
import { catchError } from 'rxjs/operators';
import { of } from 'rxjs';
import { ActivatedRoute, Router } from '@angular/router';
import { TitleService, SettingsService } from '@delon/theme';
import { Constant, ServiceResult } from '@core/constant';
import { ProductService } from '../../../../service/prod/product.service';
import { EmitterService } from 'app/service/emit.service';
import { CommService } from '../../../../service/comm/comm.service';
import { OrderService } from '../../../../service/order/order.service';
import { SimpleTableColumn, SimpleTableComponent } from '@delon/abc';

@Component({
  selector: 'order-view-edit',
  templateUrl: './order-view.component.html',
  styleUrls: ['./order-view.component.less']
})
export class OrderViewComponent implements OnInit, OnDestroy {
    sub: any;
    id;    
    order: {[proname: string]: any} = {};
    currentStep = -1;
    imgSuffix = '';
    defaultUrl = './assets/tmp/img/dummy.png';  
    // 显示图片
    previewVisible = false;
    // 大图地址
    previewImage = '';
    currency = null;
    loading = false;
    totalConfirmQty = 0;
    @ViewChild('st') st: SimpleTableComponent;
    columns: SimpleTableColumn[] = [
        { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
        { title: 'SKU', index: 'productCd', render: 'sku' },                
        { title: '数量', index: 'qty', i18n: 'qty', type: 'number' }, 
        { title: '已确认数量', index: 'confirmQty', i18n: 'confirmQty', type: 'number', },
        { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
        { title: '价格', render: 'price', i18n: 'price', type: 'currency', index: 'price' },
        { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency', index: 'totalPrice' } 
    ];

    buildColumn() {
        if (this.order.level === 'FIRST') {
            this.columns = [
                { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
                { title: 'SKU', index: 'productCd', render: 'sku' },                
                { title: '数量', index: 'qty', i18n: 'qty', type: 'number' }, 
                { title: '已确认数量', index: 'confirmQty', i18n: 'confirmQty', type: 'number', },
                { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
                { title: '价格', render: 'price', i18n: 'price', type: 'currency', index: 'price' },
                { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency', index: 'totalPrice' } 
            ]
        } else {
            this.columns = [
                { title: '', index: 'img', render: 'img', type: "img", width: "50px" },
                { title: 'SKU', index: 'productCd', render: 'sku' },                
                { title: '数量', index: 'qty', i18n: 'qty', type: 'number' },                 
                { title: '已发数量', index: 'sendQty', i18n: 'sendQty', type: 'number'  },                 
                { title: '价格', render: 'price', i18n: 'price', type: 'currency', index: 'price' },
                { title: '总价', render: 'totalPrice', i18n: 'totalPrice', type: 'currency', index: 'totalPrice' } 
            ]
        }
    }

    constructor(
        private msg: NzMessageService,
        private modalService: NzModalService,
        private productService: ProductService,
        private emit: EmitterService,
        private notification: NzNotificationService,
        private route: ActivatedRoute,
        private titleService: TitleService,
        private cnt: Constant,
        private router: Router,
        private comm: CommService,
        private orderServ: OrderService,
        private settings: SettingsService
    ) {

    }

    // 显示reusetab
    ngOnDestroy() {    
        this.emit.sendMessage("SHOW_REUSE_TAB");
    }

    ngOnInit() {
      this.currency = this.settings.user.currency;
      this.imgSuffix = this.comm.getGoodsUrl();
      // 获取参数
      this.sub = this.route.params.subscribe(params => {
        this.id = params["id"];  
        this.info();
      });
      // 隐藏reusetab
      setTimeout(() => {
          this.emit.sendMessage("HIDE_REUSE_TAB");
      }, 100);    
      this.titleService.setTitle("订单明细");    
    }

    info() {
        this.loading = true;
        this.orderServ.detail(this.id).pipe(catchError(err => {
            return of(err);
        })).subscribe(data => {
            this.loading = false;
            if (data.status === 200) {
                this.order = data.data; 
                this.setOrderStep();  
                this.buildColumn();                             
            } else {
                this.msg.error(data.message);
            }
        })
    }

    confirmQty() {
        this.totalConfirmQty = 0;
        if (this.order && this.order.details) {
            for (let i = 0; i < this.order.details.length; i++) {
                this.totalConfirmQty += this.order.details[i].confirmQty;
            }
        }
        return this.totalConfirmQty;
    }


    back() {
        this.router.navigate(['/order/myorder']);
    }

    setOrderStep() {
        if (this.order.status === 'NOCHECK') {
            this.currentStep = 0;
        } else if (this.order.status === 'CHECKED') {
            this.currentStep = 1;
        } else if (this.order.status === 'CANCEL') {
            this.currentStep = -1;
        }
       
        if (this.order.sendStatus === 'SENDING') {
            this.currentStep = 2;
        }
        if (this.order.sendStatus === 'SENDED') {
            this.currentStep = 3;
        }
    }

    showImage(src) {
        this.previewImage = src;
        this.previewVisible = true;
    }

    cancelOrder() {
        this.modalService.confirm({
            nzTitle     : 'Are you sure?',
            nzContent   : '<b style="color: red;">The order will be cancel</b>',
            nzOkText    : 'Yes', 
            nzOkType    : 'danger',           
            nzOnOk      : () => {
                this.loading = true;
                this.orderServ.cancelOrder(this.id).pipe(catchError(err => {
                    return of(err)
                })).subscribe(data => {
                    this.loading = false;
                    if (data.status === 200) {
                        this.msg.success('Successful');
                        this.info();
                        this.emit.sendMessage("RELOAD_ORDERS_LIST");
                    } else {
                        this.msg.error(data.message);
                    }
                })
            },
            nzCancelText: 'No',
            nzOnCancel  : () => {}
        });
    }

    exportDetail() {
        let exportData = this.order.details;
        for (let i = 0; i < exportData.length; i++) {
            exportData[i].price = exportData[i].price;
            exportData[i].totalPrice = exportData[i].price * exportData[i].qty;
        }
        this.st.export(exportData);
    }
}